import {messages} from "share/common";
import React from 'react';
import {connect} from 'react-redux';
import {
  Button,
  Card,
  Checkbox,
  Form,
  Radio,
  message
} from 'antd';
import airlineConfigService from './airline-config.service';
import FormItemAirlineCabin from './components/form-item-airline-cabin';
import FormItemAirlinePrice from './components/form-item-airline-price';

class AirlineConfigSearch extends React.Component {
  static cabinFieldsHelper(target, source) {
    return Object.assign({}, target, {
      isNotVisibleCabinClass: source.isEnable,
      cabinClassUserGroupId: source.controlType === 1 ? '' : source.userGroupId
    });
  }
  static ticketFieldsHelper(target, source) {
    return Object.assign({}, target, { ticketPrice: source });
  }
  static visibleFieldHelper(target, source) {
    return Object.assign({}, target, {
      visibleTicket: source.join(',')
    });
  }
  static priceFieldHelper(target, source) {
    const { priceControlReason } = source;
    return Object.assign({}, target, source, {
      priceControlReason: priceControlReason.join(',')
    });
  }
  constructor(props) {
    super(props);
    this.state = {
      isSubmitting: false
    };
  }
  componentDidMount = () => {
    const { companyOID } = this.props;
    airlineConfigService.getConfig(companyOID)('ticketQuery').then((res) => {
      if (res.data.code !== 200) return Promise.reject(res.data.message);
      const data = res.data.body;
      this.props.form.setFieldsValue({
        cabinClass: {
          isEnable: data.isNotVisibleCabinClass,
          controlType: +data.cabinClassUserGroupId ? 2 : 1,
          userGroupId: data.cabinClassUserGroupId
        },
        priceControl: {
          isPriceControl: data.isPriceControl,
          priceControlTime: data.priceControlTime,
          priceControlReason: data.priceControlReason ? data.priceControlReason.split(',') : []
        },
        visibleTicket: data.visibleTicket ? data.visibleTicket.split(',') : [],
        ticketPrice: data.ticketPrice || '3'
      });
    });
  };
  get fieldsMap() {
    return {
      cabinClass: this.constructor.cabinFieldsHelper,
      ticketPrice: this.constructor.ticketFieldsHelper,
      visibleTicket: this.constructor.visibleFieldHelper,
      priceControl: this.constructor.priceFieldHelper
    };
  }
  handleSubmit = (e) => {
    e.preventDefault();
    const { companyOID } = this.props;
    this.setState({ isSubmitting: true });
    this.props.form.validateFields((error, values) => {
      if (error) return;

      const data = Object.entries(values)
        .filter(v => v[1] !== undefined)
        .filter(([k]) => this.fieldsMap[k])
        .map(([k, v]) => ([this.fieldsMap[k], v]))
        .reduce((p, [fn, v]) => fn(p, v), {});

      airlineConfigService.updateCompanyConfig(companyOID)(data).then((res) => {
        if (res.data.code !== 200) return Promise.reject();
        return message.success(messages('common.operate.success')/*操作成功*/);
      }).catch(() => {
        message.error(messages('common.operate.filed')/*操作失败*/);
      }).finally(() => {
        this.setState({ isSubmitting: false });
      });
    });
  }
  render = () => {
    const { isSubmitting } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (<div className="airline-config-container">
      <Form onSubmit={this.handleSubmit}>
        <Form.Item>
          {getFieldDecorator('cabinClass')(
            <FormItemAirlineCabin
              title={messages('supplier.key253')/*机票舱等控制*/}
              description={messages('supplier.key254')/*默认所有员工只可见经济舱。可设置部分员工可见头等舱/商务舱*/}
              text={messages('supplier.key255')/*国内机票公务舱/头等舱预订配置*/}
            />)
          }
        </Form.Item>
        <Card type="inner" title={messages('supplier.key256')/*票价屏蔽控制*/} >
          <p className="hint">{messages('supplier.key257')/*针对同一航段*/}</p>
          <Form.Item>
            {getFieldDecorator('ticketPrice')(
              <Radio.Group>
                <Radio value={'1'}>{messages('supplier.key258')/*只显示每个舱等最低价*/}</Radio>
                <Radio value={'2'}>{messages('supplier.key259')/*只显示每个供应商每个舱等下最低价*/}</Radio>
                <Radio value={'3'}>{messages('supplier.key260')/*不限制*/}</Radio>
              </Radio.Group>
            )}
          </Form.Item>
        </Card>
        <Card type="inner" title={messages('supplier.key261')/*机票类型控制*/}>
          <p className="hint">{messages('supplier.key262')/*可见机票类型*/}</p>
          <Form.Item className="Item">
            {getFieldDecorator('visibleTicket')(
              <Checkbox.Group>
                <Checkbox value={'3'}>{messages('supplier.key265')/*共享航班*/}</Checkbox>
              </Checkbox.Group>
            )}
          </Form.Item>
        </Card>
        <Form.Item>
          {getFieldDecorator('priceControl')(<FormItemAirlinePrice />)}
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            loading={isSubmitting}
          >{messages('supplier.key250')/*保存配置*/}</Button>
        </Form.Item>
      </Form>
    </div>);
  }
}

function mapStateToProps() {
  return {};
}

const WrappedAirlineSearch = Form.create()(AirlineConfigSearch);

export default connect(mapStateToProps)(WrappedAirlineSearch);
